package org.hyperzsoft.one;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.hyperzsoft.utilities;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.content.Context;
import android.os.Process;

public class GetStandings implements Runnable {
	private static final String LOG_TAG = "GetStandings";
	
	private Thread mThread;
	private volatile boolean mStopped;
	
	public ArrayList<Team> teams = null;
	
	public GetStandings(Context context) {
		
	}
	
	public void start() {
		if (mThread == null) {
			mStopped = false;
			mThread = new Thread(this, LOG_TAG);
		}
	}
	
	public void stop() {
		if (mThread != null) {
			mStopped = true;
			mThread.interrupt();
			mThread = null;
		}
	}

	@Override
	public void run() {
		Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

		while (!mStopped) {
			try {
				Calendar cal = Calendar.getInstance();
				cal.roll(Calendar.DATE, true);
				SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

				Document doc = utilities.getDocument("http://www.nhl.com/ice/standings.htm", 
						"date", sdf.format(cal.getTime()), "season", 
						utilities.getSeasonValue(), "type", "LEA");

				Element standings = doc.body().select("tbody").get(2);

				for (Element teamRow : standings.select("tr")) {
					Team currTeam = new Team();
					currTeam.BuildTeamFromNode(teamRow);
					teams.add(currTeam);
				}

				Thread.sleep(1000);
			} catch (InterruptedException e) {
				//ignore
			}
		}
	}
}